package com.caht.controller.user.Login;

import com.caht.DTO.UserDTO;
import com.caht.entity.User;
import com.caht.Uilts.JWTUtils;
import com.caht.VO.UserLoginVO;
import com.caht.properties.jwtProperties;
import com.caht.result.Result;
import com.caht.servier.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user/login")
@Slf4j
public class phoneLogin {
    @Autowired
    private UserService userServier;
    @Autowired
    private jwtProperties jwtproperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /***
     * 获取验证码
     * @param phone
     * @return
     */
    @GetMapping("/phoneLogin/{phone}")
    public void GetPhoneCode(@PathVariable("phone")String phone){
        Integer code = userServier.GetPhoneCode(phone);
        log.info("验证码:{}",code);
        stringRedisTemplate.opsForValue().set("dog:code:"+phone, String.valueOf(code),60L, TimeUnit.SECONDS);
    }
    /**
     *  手机号登入
     */
    @PostMapping
    public Result<UserLoginVO> phoneLogin(@RequestBody UserDTO userDTO){
        // 获取验证码
        String code = stringRedisTemplate.opsForValue().get("dog:code:"+userDTO.getPhone());
        User user = null;
        // 验证验证码
        if(userDTO.getCode().equals(code)){
            // 验证成功
            user = userServier.phoneLogin(userDTO);
        }
        Map<String,Object> map = new HashMap<>();
        // 存入用户id
        map.put("userId",user.getId());
        // 获取token
        String jwt = JWTUtils.createJWT(map, jwtproperties.getUsersecret(), jwtproperties.getUserexpirationtime());
        // 封装返回值 vo
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setToken(jwt);
        BeanUtils.copyProperties(user,userLoginVO);
        return Result.success(userLoginVO);
    }
}
